package com.lagou.builder;

import com.lagou.conf.Configuration;
import com.lagou.conf.MappedStatement;
import com.mchange.v2.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> elementList = rootElement.selectNodes("//select | update");
        for (Element  element : elementList) {
            String id = element.attributeValue("id");
            String paramterType = element.attributeValue("paramterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            String key = namespace + "." + id;
            mappedStatement.setId(key);
            if (paramterType != null && !paramterType.isEmpty()) {
                mappedStatement.setParamterType(Class.forName(paramterType));
            }
            mappedStatement.setResultType(Class.forName(resultType));
            mappedStatement.setSql(sql);

            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }

}
